import { message } from 'ant-design-vue';
import * as XLSX from 'xlsx';

/**
 * 导出excel表格
 * @param data 表格数据
 * @param fileName 文件名
 * @param headers 自定义表头
 */

export async function exportAllToExcel (
    fetchAllData: () => Promise<any[]>,
    fileName: string,
    columns?: {
        key: string
        title: string
        formatter?: (value: any) => any
    }[]
){
    try{
        const allData = await fetchAllData()
        let exportData 
        if(columns){
            exportData = Array.from(allData).map(item => {
                const row: Record<string, any> = {}
                columns.forEach(col => {
                    row[col.title] = col.formatter ? col.formatter(item[col.key]) : item[col.key]
                });
                return row
            })
        }else{
            exportData = allData
        }
        const wb = XLSX.utils.book_new()
        const ws =  XLSX.utils.json_to_sheet(exportData)
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
        XLSX.writeFile(wb, `${fileName}.xlsx`)
    }catch(error){
        message.error('导出失败')
    }
    finally{
        message.success('导出完成')
    }
}

